import { Panel } from 'comps/common';
import { Table, Switch, Row, Col, Button, Modal, Icon } from 'antd';
import UserRoleAddModal from './user-role-add';
import * as React from 'react';
const { _ } = window;

const {confirm} = Modal

const RoleList = ({user, type, roles, onRoleDelete, roleAddModal }) => {

  const getTitle = ()=> {
    return type == 'company' ? "企业" : "开发组"
  }

  const roleDelete = (id)=> {
    confirm({
      title: '是否确认删除该权限?',
      onOk() {
        onRoleDelete(id, user.id)
      }
    });
  }

  const addRole = ()=> {
    roleAddModal.showModal(type, getTitle(), user)
  }

  const columns = [
    {
      title: `${getTitle()} ID`,
      dataIndex: 'targetId',
      key: 'targetId'
    }, {
      title: `${getTitle()} 名称`,
      dataIndex: 'displayName',
      key: 'displayName'
    }, {
      title: <Button type="primary" size="small" onClick={addRole}><Icon type='plus-circle-o'/></Button>,
      dataIndex: 'id',
      key: 'controll',
      render(id) {
        return <a className='color-danger' onClick={() => roleDelete(id)}>删除</a>;
      }
    }
  ];

  return (
    <Table size='middle' dataSource={roles} columns={columns} pagination={false} rowKey={record => record.id}/>
  );
};

class UserAuth extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    const {onSAEnable,onSADisable,user,roles} = this.props

    const roleListProps = {
      user: this.props.user,
      roleAddModal: this.refs.roleAddModal,
      onRoleDelete: this.props.onRoleDelete
    }

    let saRole;
    const companyAdmins = [];
    const teamLeaders = [];

    if (!_.isEmpty(roles)) {
      roles.forEach(role => {
        switch (role.role) {
          case 'SYS_ADMIN':
            saRole = role;
            break;
          case 'COMPANY_ADMIN':
            companyAdmins.push(role);
            break;
          case 'DEV_TEAM_LEADER':
            teamLeaders.push(role);
            break;
          default:
        }
      });
    }

    const onSAToggle = (enable) => {
      if (enable) {
        onSAEnable(user.id);
      } else {
        onSADisable(saRole.id, user.id);
      }
    };

    return (
      <Panel className='user-manage-roles'>
        <p>设为系统管理员：<Switch checked={saRole !== undefined} onChange={onSAToggle}/></p>
        <div className='divider'/>
        <Row>
          <Col span='10'>
            <h3 className='role-list-title'>企业管理员</h3>
            <RoleList {...roleListProps} type="company" roles={companyAdmins}/>
          </Col>
          <Col span='10' offset='4'>
            <h3 className='role-list-title'>开发组 Leader</h3>
            <RoleList {...roleListProps} type="devTeam" roles={teamLeaders}/>
          </Col>
        </Row>
        <UserRoleAddModal ref="roleAddModal" onSave={this.props.onCreateRole}/>
      </Panel>
    );
  }
}

export default UserAuth;
